// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
//     http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
//
// Author: wsfuyibing <682805@qq.com>
// Date: 2024-12-02

package publish

import (
	"encoding/json"
	"gitee.com/gomq/sr"
	"gomq/app"
)

type Request struct {
	DelaySeconds any          `json:"delay_seconds" validate:"omitempty,min=0,max=86400" label:"Delay seconds"`
	Keyword      sr.Keyword   `json:"keyword" validate:"omitempty,alphanum" label:"Keyword"`
	Message      any          `json:"message" label:"Message content" desc:"Accept json or xml"`
	Topic        sr.TopicName `json:"topic" validate:"required,min=2,max=30" label:"Topic name"`
	Tag          sr.TopicTag  `json:"tag" validate:"required,min=2,max=60" label:"Topic tag"`

	MessageBody string `json:"-" validate:"required,min=2,max=65536" label:"Message content"`
}

func (o *Request) BeforeValidate() (err error) {
	// Reset delay seconds.
	o.DelaySeconds = app.AnyInt(o.DelaySeconds, 0)

	var buf []byte
	switch o.Message.(type) {
	case string:
		o.MessageBody = o.Message.(string)
	default:
		if buf, err = json.Marshal(o.Message); err == nil {
			o.MessageBody = string(buf)
		}
	}
	return
}
